import cv2
import os
import threading
import time
from datetime import datetime
from queue import Queue, Empty


"""
    看都不用看，根本没用上
stream_manager
    init
        # 创建持续录制器（参数可从配置文件读取，也可写死）
        always_record_cfg = self.config.get('always_recording', {})
        self.always_recorder = ContinuousVideoRecorder(
            output_dir=always_record_cfg.get('output_dir', 'data/continuous_recordings'),
            frame_width=self.config['video']['frame_width'],
            frame_height=self.config['video']['frame_height'],
            fps=self.config['video']['fps'],
            segment_seconds=always_record_cfg.get('segment_seconds', 1200)  # 20分钟
        )
    start
        self.always_recorder.start()  # 启动持续录制
    loop
                    # 持续录制：无论什么情况都录制
                self.always_recorder.add_frame(frame)
"""



class ContinuousVideoRecorder:
    def __init__(self, output_dir, frame_width, frame_height, fps=10, segment_seconds=1200):
        self.output_dir = output_dir
        self.frame_width = frame_width
        self.frame_height = frame_height
        self.fps = fps
        self.segment_seconds = segment_seconds  # 每段时长（秒）
        self.frame_queue = Queue(maxsize=100)
        self.is_running = False
        self.recording_thread = None
        os.makedirs(self.output_dir, exist_ok=True)

    def start(self):
        self.is_running = True
        self.recording_thread = threading.Thread(target=self._record_loop)
        self.recording_thread.daemon = True
        self.recording_thread.start()

    def stop(self):
        self.is_running = False
        if self.recording_thread:
            self.recording_thread.join(timeout=5)

    def add_frame(self, frame):
        # 丢弃队列中最老的帧，保证低延迟
        while self.frame_queue.qsize() > 80:
            try:
                self.frame_queue.get_nowait()
            except Empty:
                break
        self.frame_queue.put(frame)

    def _record_loop(self):
        fourcc = cv2.VideoWriter_fourcc(*'mp4v')
        writer = None
        segment_start_time = None
        filename = None

        while self.is_running:
            try:
                frame = self.frame_queue.get(timeout=1)
            except Empty:
                continue

            now = time.time()
            if writer is None or (now - segment_start_time) >= self.segment_seconds:
                # 关闭旧文件
                if writer is not None:
                    writer.release()
                    print(f"[持续录制] 保存视频: {filename}")
                # 新文件名
                timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                filename = os.path.join(self.output_dir, f"continuous_{timestamp}.mp4")
                writer = cv2.VideoWriter(filename, fourcc, self.fps, (self.frame_width, self.frame_height))
                segment_start_time = now
                print(f"[持续录制] 开始新视频: {filename}")

            # 写入帧
            if frame.shape[1] != self.frame_width or frame.shape[0] != self.frame_height:
                frame = cv2.resize(frame, (self.frame_width, self.frame_height))
            writer.write(frame)

        # 退出时关闭文件
        if writer is not None:
            writer.release()
            print(f"[持续录制] 保存视频: {filename}")
